package com.greenlife.service.impl;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.greenlife.commom.FileFormatConstant;
import com.greenlife.commom.ResponseException;
import com.greenlife.common.enums.BaseResultCodeEnum;
import com.greenlife.controller.util.HttpUtil;
import com.greenlife.controller.util.RandomUtil;
import com.greenlife.model.FileServerConfig;
import com.greenlife.service.FileServerClient;
@Service("fileServerClient")
public class FileServerClientImpl implements FileServerClient {
    private final static Logger logger = LoggerFactory.getLogger(FileServerClientImpl.class);

    @Autowired
    private FileServerConfig fileServerConfig;

    public String uploadFile(MultipartFile file) { 
    	  	String name = file.getOriginalFilename();
    	    String suffix = name.substring(name.lastIndexOf(".")+1);
    	    if(suffix==null || !FileFormatConstant.SUFFIX_TYPE.contains(suffix.toLowerCase())){
        		throw new ResponseException(BaseResultCodeEnum.ERR_CODE_30010);
       		 }else if(fileServerConfig.getMaxUploadSize() < file.getSize()){
       			throw new ResponseException(BaseResultCodeEnum.ERR_CODE_20030);
       		 }
            DateFormat format = new SimpleDateFormat("yyyymmddhhmmssSSS");
            name = format.format(new Date())+RandomUtil.getRandomRandom(15)+"."+suffix;
            if(SCHEME_HTTP.equals(fileServerConfig.getScheme())){
            	return fileServerConfig.getDomain()+uploadHttp(file,name);
            }else if(SCHEME_LOCAL.equals(fileServerConfig.getScheme())) {
				return uploadLocal(file, name);
			}else{
				throw new ResponseException(BaseResultCodeEnum.ERR_CODE_00008);
			}
    }

    private String uploadHttp(MultipartFile file,String name) {
    	String boundary = "-----------------123456789987654321";
    	try {
			URL url = new URL(fileServerConfig.getUpLoadUrl());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    		conn.setConnectTimeout(5000);  
            conn.setReadTimeout(30000);  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);  

            OutputStream out = new DataOutputStream(conn.getOutputStream());
            StringBuffer strBuf = new StringBuffer();  
            strBuf.append("\r\n").append("--").append(boundary).append("\r\n");  
            strBuf.append("Content-Disposition: form-data; name=file; filename=\"" + name+ "\"\r\n");  
            strBuf.append("Content-Type:" + file.getContentType() + "\r\n\r\n");  
            out.write(strBuf.toString().getBytes());  
            out.write(file.getBytes());
            byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();  
            out.write(endData);  
            out.flush();  
            out.close();  
            String result = HttpUtil.streamChangeToString(conn.getInputStream());
            ObjectMapper mapper = new ObjectMapper();  
            JsonNode resultNode = mapper.readTree(result); 
            if(resultNode.get("success").asBoolean()){
            	JsonNode dataNode = resultNode.get("data");	
               return dataNode.get(0).asText();
            }else {
            	throw new ResponseException(BaseResultCodeEnum.ERR_CODE_30006);
			}     
		} catch (Exception e) {
			throw new ResponseException(BaseResultCodeEnum.ERR_CODE_30006);
		}

    }
    
	public String uploadLocal(MultipartFile file,String name){
		@SuppressWarnings("unused")
		String path;
		try {
		FileOutputStream fos = null;
		InputStream is = file.getInputStream();
		byte[] buffer = new byte[1024];
		fos = new FileOutputStream(new File(fileServerConfig.getRoot()+fileServerConfig.getPath()+name));
		while ((is.read(buffer))!=-1) {
			fos.write(buffer);
		}
		fos.flush();
	    fos.close();
	    if(fileServerConfig.getPath()!=null)
 			 path = fileServerConfig.getPath().replace("\\", "/");
 		 else{
 			 logger.info("文件服务器配置错误：资源路径不能为空");
 			 throw new ResponseException(BaseResultCodeEnum.ERR_CODE_00000);
 		 }
		}
	    catch (Exception e) {
	    	throw new ResponseException(BaseResultCodeEnum.ERR_CODE_30006);  
		}
	    return name;
}    
}